/**
 * 
 */
package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

/**
 * Normalize input coordinates with a specified factor.
 * 
 * @author Xiaohui
 * 
 */

public class Normalization {
	// double xextent;
	// double yextent;
	double scaleFactor;
	static int decimalplace = 6;
	DecimalFormat formatter;

	public Normalization() {
		formatter = new DecimalFormat("#0.000000");
	}

	public Normalization(double scaleFactor) {
		this.scaleFactor = scaleFactor;
		formatter = new DecimalFormat("#0.000000");
	}

	// public Normalization(double x_extent, double y_extent) {
	// this.xextent = x_extent;
	// this.yextent = y_extent;
	// }
	//
	// public void setExtent(double x_extent, double y_extent) {
	// this.xextent = x_extent;
	// this.yextent = y_extent;
	// }

	/**
	 * Line can be commented with #
	 * 
	 * @param inFilename
	 * @param xcol
	 *            : x coord col number, number from 1
	 * @param ycol
	 *            : y coord col number, number from 1
	 * @param outFilename
	 */

	public void normalize(String inFilename, int xcol, int ycol,
			String outFilename, String delim) {
		BufferedReader in;
		BufferedWriter out;
		try {
			in = new BufferedReader(new FileReader(inFilename));
			out = new BufferedWriter(new FileWriter(outFilename));
			String str;
			while ((str = in.readLine()) != null) {
				if (str.startsWith("#")) {
					out.write(str);
					out.newLine();
					continue;
				}
				String temp = normalize(str, xcol, ycol, delim);
				out.write(temp);
				out.newLine();
			}
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	String normalize(String str, int xcol, int ycol, String delim) {
		StringTokenizer st = new StringTokenizer(str, delim);
		String temp = "";

		// loop to specific location
		int i = 1;
		for (; i < xcol; i++) {
			temp += st.nextToken() + delim;
		}
		temp += formatter.format(Double.parseDouble(st.nextToken())
				* scaleFactor)
				+ delim;
		i++;
		for (; i < ycol; i++) {
			temp += st.nextToken() + delim;
		}
		temp += formatter.format(Double.parseDouble(st.nextToken())
				* scaleFactor)
				+ delim;
		// get remaining
		while (st.hasMoreElements()) {
			temp += st.nextToken() + delim;
		}
		return temp;
	}

	public static void main(String[] args) {
		double factor = 0.01;
		Normalization n = new Normalization(factor);

		String delim = " ";
		String str = "a 325.734848 600.837376 b";
		String in = "D:/Research/trajectory indexing/temp/traj.txt";
		String out = "D:/Research/trajectory indexing/temp/tt.txt";
		n.normalize(in, 3, 4, out, "\t");
		System.out.println(n.normalize(str, 2, 3, delim));
	}

}
